package io.yyxx.boot.util;

import io.yyxx.boot.business.service.impl.MyStart;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;

@Component
public class ScheduledTaskService {
    private static final Logger log = LoggerFactory.getLogger(ScheduledTaskService.class);
    
    private final MyStart start;

    // 通过构造器注入
    public ScheduledTaskService(MyStart start) {
        this.start = start;
    }

    /**
     * 定时任务
     * 程序启动后5秒钟后开始执行
     * 每小时执行一次（整点执行）
     * cron表达式说明：秒 分 时 日 月 周
     */
//    @Scheduled(initialDelay = 5_000, fixedRate = 5_000)//用于测试，每5秒执行一次
    @Scheduled(initialDelay = 5_000, fixedRate = 3_600_000)
    public void executeEveryMinute() {
        long startMs = System.currentTimeMillis();

        try {
            LocalDateTime startNow = LocalDateTime.now();
            log.info(startNow+"开始执行定时任务...");
            start.pullForAlitrip();
            start.saveToYiDa();
            LocalDateTime endNow = LocalDateTime.now();
            log.info(endNow+"定时任务执行完成");

        } catch (Exception e) {
            LocalDateTime now = LocalDateTime.now();
            log.error(now+"定时任务执行失败", e);
        }finally {
            long durationMs = System.currentTimeMillis() - startMs;
            log.info("定时任务执行完成，耗时 {} 毫秒", durationMs);
            log.info("==========================================================================================================================================");
        }
    }
}